package cn.ljy.authority.model.dto;

import cn.ljy.authority.model.SysPermission;
import cn.ljy.authority.model.SysUser;
import com.alibaba.fastjson.annotation.JSONField;
import lombok.Data;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.util.StringUtils;

import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 针对spring security使用的账户对象
 */
@Data
public class SysUserAuthority extends SysUser implements UserDetails {

	private static final long serialVersionUID = -1379274258881257107L;

	private List<SysPermission> sysPermissions;//拥有的权限集合

	//将权限信息变为spring security认可的权限对象集合
	@Override
	@JSONField(serialize=false) //不将其转换为JSON
	public Collection<? extends GrantedAuthority> getAuthorities() {
		return sysPermissions.parallelStream()
				.filter(p -> StringUtils.hasLength(p.getPermission())&&p.getEnabled()==true) // 过滤出没有权限标识，并且可用的权限
				.map(p -> new SimpleGrantedAuthority(p.getPermission()))
				.collect(Collectors.toSet());
	}

	// 账户是否未过期
	@JSONField(serialize=false) //不将其转换为JSON
	@Override
	public boolean isAccountNonExpired() {
		return true;
	}

	// 账户是否未锁定
	@JSONField(serialize=false) //不将其转换为JSON
	@Override
	public boolean isAccountNonLocked() {
		return super.getStatus()!=SysUserStatus.LOCKED;
	}

	// 密码是否未过期
	@JSONField(serialize=false) //不将其转换为JSON
	@Override
	public boolean isCredentialsNonExpired() {
		return true;
	}

	// 账户是否激活
	@JSONField(serialize=false) //不将其转换为JSON
	@Override
	public boolean isEnabled() {
		return true;
	}

}
